package com.gopay.webtest.controller.entrustpay;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.time.StopWatch;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.webtest.controller.base.BaseController;
import com.gopay.webtest.util.BaseSign;
import com.gopay.webtest.util.DateUtils;
import com.gopay.webtest.util.ReflectUtil;
import com.gopay.webtest.vo.entrustpay.EntrustPayVO;
import com.gopay.webtest.xml.XmlDao;

/** 
 * @ClassName: EntrustPayController 
 * @Description: 委托代收Controller
 * @author lx 
 * @date 2016年12月20日 下午6:35:21  
 */
@RequestMapping("/entrustPay")
@Controller
public class EntrustPayController  extends BaseController {
    @Resource(name = "xmlDao")
    private XmlDao xmlDao;
    
    @Resource(name = "entrustPaySignHandler")
    private BaseSign entrustPaySignHandler;

    /** 
     * @Description: 发起委托代收请求
     * @return 
     * @author lx 
     */
    @RequestMapping("/transApi")
    public ModelAndView transAPIReq(HttpServletRequest req ) {
        ModelAndView mv = new ModelAndView();

        try {
            Map<String, String> map = xmlDao.readData4Map("ds_trans_api", "trans");
            String URL= req.getRequestURL().toString();
            String host=URL.replace("/webtest/entrustPay/transApi.do","") ;
            if (map.containsKey("tranDateTime")) {
                map.remove("tranDateTime");
                map.remove("gopayServerTime");
                map.remove("tranIP");
                map.put("tranDateTime", DateUtils.format(new Date(), "yyyyMMddHHmmss"));
                map.put("gopayServerTime", DateUtils.format(new Date(), "yyyyMMddHHmmss"));
                map.put("tranIP", getRemoteRealIpAddr(req));
                map.put("backgroundMerUrl", host+"/webtest"+map.get("backgroundMerUrl"));
            }

            mv = new ModelAndView("entrustpay.transApi");
            mv.addObject("transInfo", map);
        } catch (Exception e) {
            logger.error("错误提示", e);
        }

        return mv;
    }
    
    /** 
     * @Description: 处理交易的参数
     * @return 
     * @author lx
     */
    @RequestMapping("/doTransApi")
    public ModelAndView doTransAPIReq(EntrustPayVO vo,HttpServletRequest req ) {
        ModelAndView mv = new ModelAndView();
        StopWatch sw  = new StopWatch(); //执行效率监视器
        sw.start();
        //logger.debug();
        //处理参数 封装xml 报文发送到网关 并且接受返回参数
        try {
            entrustPaySignHandler.sign(vo.getTranCode() + "_" + vo.getVersion(), "signType", "signValue", vo, getRequest());
            ReflectUtil.desField(vo, vo.getVerficationCode());
            System.out.println("signValue = "+vo.getSignValue());
            // 报文发送到网关 
            logger.info("send data to gateway...");
            // 接受返回参数
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!vo.getCharset().equals("2")) {
            mv.setViewName("entrustpay.transApi.gbk");
        } else {
            mv.setViewName("entrustpay.transApi.utf8");
        }
        mv.addObject("payInfo", vo);
        sw.stop();
        logger.info("spend time:"+sw.getTime());
        // logger.info("后台notify密文值:" + vo.getSignValue());
        return mv;
    }

    /**
     * 将Request中的数据转换成Map
     */
    @SuppressWarnings("rawtypes")
    Map<String, String> listParameters(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        for (Enumeration enumeration = request.getParameterNames(); enumeration.hasMoreElements();) {
            String eleName = (String) enumeration.nextElement();
            String eleValue = request.getParameter(eleName);
            logger.error("网关收到的请求参数键: [" + eleName + "]，值: [" + eleValue + "]");
            params.put(eleName, eleValue);
        }
        return params;
    }

}
